<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <buttton id="btn">发送ajax请求</buttton>
    <script>
      function myAjax(options) {
        if (!options) return
        let {
          url,
          method = "get",
          data,
          timeout = 2000,
          dataType,
          success,
          error,
          complete,
          beforeSend,
        } = options
        if (!url) return
        const xhr = new XMLHttpRequest()
        let params = boj2str(data)
        if(method === "get" && params){
            url += `?${params}`
            parmas = null
        }
        xhr.open(method,url)
        if(method === "post"){
            xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
        }
        const result = beforeSend && beforeSend()
        if(result === false) return
        xhr.send(params)
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                complete && complete()
                if(xhr.status === 200){
                    let data = xhr.responseText
                    if(dataType === "json"){
                        try{
                            data = JSON.parse(data)
                        }catch(err){
                            
                        }
                    }
                }
            }
        }
      }

      function obj2str(data){
        if(!data) return
        let arr = []
        for(let key in data){
            arr.push(`${key}=${data[key]}`)
        }
        return arr.join("&")
      }

      const btn = document.querySelector("#btn")
      btn.onclick = function () {
        myAjax({
          url: "http:localhost:5000/test",
          method: "post",
          data: {
            name: "轩轩",
            age: 10,
          },
          //   timeout: 5000,
          //   dataType: "text",
          success() {
            console.log("响应成功")
          },
          error() {
            console.log("响应失败")
          },
          complete() {
            console.log("响应完成")
          },
          beforeSend() {
            console.log("响应之前发送")
          },
        })
      }
    </script>
  </body>
</html>
